package com.cdream.basic.algorithm.leetcode.dp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cdream
 * @date 6/2/21
 */
public class Question40 {
    private List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, 0, target, new ArrayList<>());
        return res;
    }

    private void dfs(int[] candidates, int index, int target, List<Integer> midList) {

        if (target == 0) {
            res.add(new ArrayList<>(midList));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] > target) {
                return;
            }
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            midList.add(candidates[i]);
            dfs(candidates, i + 1, target - candidates[i], midList);
            midList.remove(midList.size() - 1);
        }

    }
}
